package com.yosaa.back.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yosaa.back.entity.*;
import com.yosaa.back.entity.vo.LoginInfoVO;
import com.yosaa.back.service.*;
import com.yosaa.back.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService usersService;


    @PostMapping("/login")
    public ResponseEntity doLogin(@RequestBody UserInfo user) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("email", user.getEmail());
        wrapper.eq("password", user.getPassword());
        UserInfo u = usersService.getOne(wrapper);
        if(u != null) {
            StpUtil.login(u.getUserId());
            LoginInfoVO loginInfo = new LoginInfoVO();
            loginInfo.setToken(StpUtil.getTokenValue());
            loginInfo.setUserId(u.getUserId());
            loginInfo.setUsername(u.getUsername());
            loginInfo.setImgUrl(u.getImgUrl());
            return ResponseEntity.ok(new ApiResponse(0, loginInfo, "操作成功"));
        }
        return ResponseEntity.ok(new ApiResponse(1, null, "操作失败"));
    }

    @GetMapping("/info")
    public ResponseEntity loginInfo() {
        if(StpUtil.isLogin()){
            UserInfo u = usersService.getById((Serializable) StpUtil.getLoginId());
            LoginInfoVO loginInfo = new LoginInfoVO();
            loginInfo.setToken(StpUtil.getTokenValue());
            loginInfo.setUserId(u.getUserId());
            loginInfo.setImgUrl(u.getImgUrl());
            loginInfo.setRoles("1".equals(u.getRole()) ?
                    new ArrayList<>(List.of("user")) :
                    new ArrayList<>(List.of("admin")));
            return ResponseEntity.ok(new ApiResponse(0, loginInfo, "操作成功"));
        }else return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("操作失败");
    }


    @PostMapping("/logout")
    public ResponseEntity logout() {
        StpUtil.logout();
        return ResponseEntity.ok(new ApiResponse(0, null, "退出登录成功"));
    }

    @GetMapping("/{userId}")
    public ResponseEntity<UserInfo> getUserById(@PathVariable Integer userId) {
        UserInfo user = usersService.getById(userId);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    @GetMapping("/list")
    public ResponseEntity getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer role,
            @RequestParam(required = false) Integer disable) {

        Page<UserInfo> userPage = new Page<>(page, size);

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.trim().isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (role != null) {
            queryWrapper.eq("role", role);
        }
        if (disable != null) {
            queryWrapper.eq("disable", disable);
        }

        IPage<UserInfo> result = usersService.page(userPage, queryWrapper);
        return ResponseEntity.ok(new ApiResponse(0, result, "操作成功"));
    }


    @PostMapping("/add")
    public ResponseEntity addUser(@RequestBody UserInfo user) {
        boolean saved = usersService.save(user);
        if (saved) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "Failed"));
        }
    }

    @PostMapping("/update")
    public ResponseEntity updateUser(@RequestBody UserInfo user) {
        boolean updated = usersService.updateById(user);
        if (updated) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "Failed"));
        }
    }

    @DeleteMapping("/delete/{userId}")
    public ResponseEntity deleteUser(@PathVariable Integer userId) {
        boolean removed = usersService.removeById(userId);
        if (removed) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "Failed"));
        }
    }
}
